package javabase.demo02;

import java.lang.reflect.Field;
import java.util.*;

public class ListPractice {
    public static void main(String[] args) {
        List<String> arrayList = new ArrayList<>();

        arrayList.add("Java");
        arrayList.add("Python");
        arrayList.add("C++");
        arrayList.add(1, "JavaScript"); // 在指定位置插入

        System.out.println("ArrayList: " + arrayList);

        // 访问元素
        System.out.println("第一个元素: " + arrayList.get(0));
        System.out.println("包含Java吗? " + arrayList.contains("Java"));

        // 修改元素
        arrayList.set(2,"Go");
        System.out.println("修改后: " + arrayList);

        // 删除元素
        arrayList.remove("C++");
        arrayList.remove(0);
        System.out.println("删除后: " + arrayList);

        // 遍历
        System.out.println("=== 遍历ArrayList ===");
        for(int i=0; i < arrayList.size(); i++){
            System.out.println("索引 " + i + ": " + arrayList.get(i));
        }
        // 2. 增强for循环
        for (String language : arrayList) {
            System.out.println("语言: " + language);
        }

        // 3. 迭代器
        Iterator<String> iterator = arrayList.iterator();
        while (iterator.hasNext()){
            System.out.println("迭代器: " + iterator.next());
        }

        // 4. forEach方法 (Java 8+)
        arrayList.forEach(lang -> System.out.println("forEach: " + lang));

        // LinkedList - 基于双向链表
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.add("Apple");
        linkedList.add("Banana");
        linkedList.addFirst("Orange"); // 链表头部添加
        linkedList.addLast("Grape");   // 链表尾部添加

        System.out.println("LinkedList: " + linkedList);

        System.out.println("第一个元素: " + linkedList.getFirst());
        System.out.println("最后一个元素: " + linkedList.getLast());
        linkedList.removeFirst();
        linkedList.removeLast();
        System.out.println("删除首尾后: " + linkedList);

        // Vector - 线程安全的ArrayList (已过时，不推荐使用)
        Vector<String> vector = new Vector<>();
        vector.add("Element1");
        vector.add("Element2");
        System.out.println("Vector: " + vector);
    }


}
